// pages/otherIndex/otherIndex.js
import request from '../../../utils/config.js';
import encode from '../../../utils/base64.js';
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    ossImgUrL: 'https://winhc.oss-cn-shanghai.aliyuncs.com/xcx/',
    otherPerInfo: null,
    otherOpenid: "",
    showlocation: "none",
    seeNum:0,
    favorNum:0,
    msgNum:0,
    voteNum:0,
    vote: false,
    voteRenqi:true,
    fieldArea: "未填写",
    favor:false,
    animationzanData: {},
    animationrenqiData: {},
    imgList: new Array(),
    showModel: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showShareMenu({
      withShareTicket: true
    })
    var tempMockData = {
      avatarUrl: "https://winhc.oss-cn-shanghai.aliyuncs.com/xcx/nick.png",
      userName: "暂无",
      mobileNo: "暂无",
      lawfirmName: "暂无",
      title: "暂无",
      email: "暂无",
      moreExt: "暂无"
    };
    let _that = this;
    
    this.setData({
      otherPerInfo: tempMockData
    });
    console.log("此处打印的options=", options)
    console.log("此处可以拿到转发的openid=", options.openid)
    this.setData({
      otherOpenid: options.openid
    });
    //存储otherOpenId
    wx.setStorageSync("otherOpenid", this.data.otherOpenid);
    if (!app.globalData.userInfo) {
      // 获取用户信息
      let _that = this;
      app.getAuthUserInfo((res)=>{
        // 可以将 res 发送给后台解码出 unionId
        res.userInfo.nickName = res.userInfo.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
        app.globalData.userInfo = res.userInfo;
        wx.showLoading({
          title: '加载中',
        })
        _that.getOpenid(_that);
      },(res)=>{
        console.log("获取用户信息失败=", res)
        _that.setData({
          showModel: true
        })
      });
    } else {
      this.getOtherUserInfo(this);
    }
    let bodyInfo = {
      openid: app.globalData.openid,
      otherOpenid: this.data.otherOpenid
    };
    let otherOpenid = this.data.otherOpenid;
    request.get_api("meLikeWho", bodyInfo, (data) => {
      // console.log("我喜欢谁", data.data.body)
      let meLikeOpenId = JSON.parse(data.data.body)
      for (let i = 0; i < meLikeOpenId.length; i++) {
        if (otherOpenid == meLikeOpenId[i].openid) {
          _that.setData({
            vote: true
          })
        }
      }
    }, (data) => {
      console.log("取消点赞失败", data)
    });
  },

  //组件授权回调
  _setAuthorization: function (e) {
    let that = this;
    let res = e.detail;
    that.getOpenid(that);
  },

  //获取openid
  getOpenid: (_that) => {
    // console.log('获取openid------->',app.globalData.code);
    request.request_api(app.globalData.code, (data) => {
      console.log("openid成功", data)
      app.globalData.openid = data.data.openid;
      app.globalData.session_key = data.data.session_key;
      _that.getLoginInfo(_that);
    }, (data) => {
      wx.hideLoading();
      console.log("openid失败", data)
    });
  },

  //获取登录信息
  getLoginInfo: (_that) => {
    //获取第三方接口登录数据
    let bodyInfo = {
      openid: app.globalData.openid
    };
    request.get_api("login", bodyInfo, (res) => {
      wx.hideLoading();
      console.log("登录成功=", res)
      if (res.data.isSuccess == 'T') {
        //保存数据
        let bodyData = JSON.parse(res.data.body);
        app.globalData.persionalInfo = bodyData;
        _that.getOtherUserInfo(_that);
      } else {

      }
    }, (res) => {
      wx.hideLoading();
      console.log("登录失败=", res)
    });
  },


  //根据openid获取用户信息
  //获取登录信息
  getOtherUserInfo: function (_that){
    //获取第三方接口登录数据
    wx.showLoading({
      title: '加载中',
    })
    let bodyInfo = {
      openid: app.globalData.openid,
      otherOpenid: _that.data.otherOpenid,
      nickName: app.globalData.userInfo.nickName,
      avatarUrl: app.globalData.userInfo.avatarUrl
    };
    console.log("bodyInfo=",bodyInfo)
    if (app.globalData.userInfo) {
      console.log('获取自身=',app.globalData.userInfo);
    }
    request.get_api("getUsers", bodyInfo, (res) => {
      wx.hideLoading();
      console.log("登录成功=", res)
      if (res.data.isSuccess == 'T') {
        //保存数据
        let bodyData = JSON.parse(res.data.body).memUserInfo;
        let tempImgList = new Array;
        if (bodyData.images) {
          tempImgList = JSON.parse(bodyData.images);
        }
        let showlocationFlag = 'none';
        if (bodyData.address) {
          showlocationFlag = 'block';
        } else {
          showlocationFlag = 'none';
        }
        let advField = "未填写";
        if (bodyData.advField) {
          advField = bodyData.advField.replace(/,/g, " | ");
        }

        //人气动画效果
        var animation = wx.createAnimation({
          duration: 1000,
          timingFunction: 'ease',
        })
        this.animation = animation;
        animation.opacity(1).translateY(-26).scale(1.5, 1.5).step();
        if (bodyInfo.openid == bodyInfo.otherOpenid) {
          // console.log('自己的')
          _that.setData({
            otherPerInfo: bodyData,
            imgList: tempImgList,
            seeNum: bodyData.seeNum,
            favorNum: bodyData.favorNum,
            msgNum: bodyData.msgNum,
            voteNum: bodyData.voteNum,
            voteRenqi: bodyData.vote,
            favor: bodyData.favor,
            fieldArea: advField,
            showlocation: showlocationFlag
          });
        } else if (bodyInfo.openid != bodyInfo.otherOpenid) {
          _that.setData({
            otherPerInfo: bodyData,
            imgList: tempImgList,
            seeNum: bodyData.seeNum,
            favorNum: bodyData.favorNum,
            msgNum: bodyData.msgNum,
            voteNum: bodyData.voteNum,
            voteRenqi: bodyData.vote,
            favor: bodyData.favor,
            fieldArea: advField,
            animationrenqiData: animation.export(),
            showlocation: showlocationFlag
          });
          setTimeout(function () {
            animation.opacity(0).translateY(0).scale(1, 1).step()
            _that.setData({
              animationrenqiData: animation.export()
            })
          }.bind(this), 1500)
        }
        let tempName = bodyData.nickName;
        if (bodyData.userName){
          tempName = bodyData.userName;
        }
        wx.setNavigationBarTitle({ title: tempName+'的名片' })
        
      } 
    }, (res) => {
      wx.hideLoading();
      console.log("登录失败=", res)
    });
  },

  //拨打电话
  callPhone: function () {
    var _this = this;
    wx.getSystemInfo({
      success: function(res) {
        console.log(res.system)
        let phoneVal = res.system;
        if (phoneVal.indexOf('iOS') != -1) {
          wx.makePhoneCall({
            phoneNumber: _this.data.otherPerInfo.mobileNo //仅为示例，并非真实的电话号码
          })
        } else if (phoneVal.indexOf('Android') != -1) {
          wx.showModal({
            title: '提示',
            content: '确定呼出电话？',
            success: function(res) {
              if (res.confirm) {
                wx.makePhoneCall({
                  phoneNumber: _this.data.otherPerInfo.mobileNo //仅为示例，并非真实的电话号码
                })
              } else if (res.cancel) {

              }
            }
          })
        }
      },
    })
    
  },
  // 点人气
  clickRenqi: function(){
    let bodyInfo = {
      openid: app.globalData.openid,
      otherOpenid: this.data.otherOpenid
    };
    if (bodyInfo.openid == bodyInfo.otherOpenid) {
      wx.showModal({
        title: '提示',
        content: '去个人名片查看我的人气吧',
        showCancel: false,
        confirmColor: '#1b82d1'
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '你没有权限查看对方人气喔',
        showCancel: false,
        confirmColor: '#1b82d1'
      })
    }
  },

  //点赞
  clickZan: function(){
    let vote = this.data.vote;
    let voteNum = this.data.voteNum;
    // let otherOpenid;
    let bodyInfo = {
      openid: app.globalData.openid,
      otherOpenid: this.data.otherOpenid
    };
    let _that = this;
    
    if (bodyInfo.openid == bodyInfo.otherOpenid) {
      wx.showModal({
        title: '提示',
        content: '你不能给自己点赞喔',
        showCancel: false,
        confirmColor: '#1b82d1'
      })
    } else {
      if (vote) {  //如果true 去取消点赞
        request.post_api("unlike", bodyInfo, (data) => {
          console.log("取消点赞成功", data)
          let voteNumnum = voteNum - 1;
          if (voteNumnum<0) {
            voteNumnum =0;
          } 
          _that.setData({
            voteNum: voteNumnum,
            vote: false
          });
        }, (data) => {
          console.log("取消点赞失败", data)
        });
      } else {  //如果false 去点赞
        request.post_api("like", bodyInfo, (data) => {
          console.log("点赞成功", data)
          var animation = wx.createAnimation({
            duration: 1000,
            timingFunction: 'ease',
          })
          this.animation = animation
          animation.opacity(1).translateY(-26).scale(1.5, 1.5).step()
          _that.setData({
            voteNum: voteNum + 1,
            vote: true,
            animationzanData: animation.export()
          });
          setTimeout(function () {
            animation.opacity(0).translateY(0).scale(1, 1).step()
            _that.setData({
              animationzanData: animation.export()
            })
          }.bind(this), 1500)
        }, (data) => {
          console.log("点赞失败", data)
        });
      }
    }

      
  },

  //留言
  clickLiuyan: function(){
    console.log(app.globalData.persionalInfo);
    let bodyInfo = {
      openid: app.globalData.openid,
      otherOpenid: this.data.otherOpenid
    };
    let userName = app.globalData.persionalInfo.userName;
    if (bodyInfo.openid == bodyInfo.otherOpenid) {
      wx.showModal({
        title: '提示',
        content: '你不能给自己留言喔',
        showCancel: false,
        confirmColor: '#1b82d1'
      })
    } else {
      if (userName != null) {
        wx.navigateTo({
          url: '../toliuyan/toliuyan',
        })
      } else if (userName == null) {
        wx.showModal({
          title: '提示',
          content: '完善自己的名片才可以给对方留言喔',
          showCancel: false,
          confirmColor: '#1b82d1'
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.toast = this.selectComponent("#toast");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showShareMenu({
      withShareTicket: true
    })
    //放进名片夹
    let bodyInfo = {
      openid: app.globalData.openid,
      otherOpenId: this.data.otherOpenid
    };
    let _that = this;
    request.post_api("addCardClip", bodyInfo, (data) => {
      console.log("添加名片夹成功", data)
      let bodyInfo = JSON.parse(data.data.body);
      _that.setData({
        msgNum: bodyInfo.msgNum,
        favor: true
      });
    }, (data) => {
      console.log("添加名片夹失败", data)
    });
  },

  //点击图片预览
  showPic: function () {
    var picUrl = this.data.otherPerInfo.avatarUrl;
    wx.previewImage({
      current: picUrl, // 当前显示图片的http链接
      urls: [picUrl] // 需要预览的图片http链接列表
    })
  },

  //返回名片
  goHomePage: function(){
    wx.navigateTo({
      url: '../cardIndex/cardIndex'
    })
  },

  //同步手机通讯录
  syncDressBook: function(){
    // wx.switchTab({
    //   url: '../index/index'
    // })
    let savedFilePath = "";
    let _that = this;
    wx.downloadFile({
      url: _that.data.otherPerInfo.avatarUrl,
      success: function (res) {
        savedFilePath = res.tempFilePath
        wx.addPhoneContact({
          photoFilePath: savedFilePath,
          firstName: _that.data.otherPerInfo.userName,
          organization: _that.data.otherPerInfo.lawfirmName,
          title: _that.data.otherPerInfo.title,
          workPhoneNumber: _that.data.otherPerInfo.mobileNo,
          email: _that.data.otherPerInfo.email,
          homeAddressStreet: _that.data.otherPerInfo.address,
          success: function (res) {
            console.log("同步到手机通讯录成功");
            wx.showToast({
              title: '同步成功',
              icon: 'success',
              duration: 1000
            })
          },
          fail: function (res) {
            console.log("同步到手机通讯录失败")
          }
        });
      },
      fail: function(res){
        console.log("下载失败=",res)
      }
    })
  },

  //放入名片夹
  putCardHolder: function(){
    let favor = this.data.favor;
    let _that = this;
    if(favor){
      //移除名片夹
      let bodyInfo = {
        openid: app.globalData.openid,
        otherOpenId: this.data.otherOpenid
      };
      request.post_api("delCardClip", bodyInfo, (data) => {
        console.log("移除名片夹成功", data)
        let bodyInfo = JSON.parse(data.data.body);
        _that.setData({
          favorNum: bodyInfo.favorNum,
          favor: false
        });
      }, (data) => {
        console.log("移除名片夹失败", data)
      });
    }else{
      //放进名片夹
      let bodyInfo = {
        openid: app.globalData.openid,
        otherOpenId: this.data.otherOpenid
      };
      request.post_api("addCardClip", bodyInfo, (data) => {
        console.log("添加名片夹成功", data)
        let bodyInfo = JSON.parse(data.data.body);
        _that.setData({
          favorNum: bodyInfo.favorNum,
          favor: true
        });
      }, (data) => {
        console.log("添加名片夹失败", data)
      });
    }
  },

  //显示图片
  showIndexImage: function (e) {
    //存储需要的数据
    let tempData = {
      avatarUrl: this.data.otherPerInfo.avatarUrl,
      userName: this.data.otherPerInfo.userName,
      time: this.data.otherPerInfo.openTime,
      images: JSON.parse(this.data.otherPerInfo.images)
    }
    wx.setStorageSync('showMoreImgList', tempData);
    var indexKey = e.target.dataset.key;
    wx.navigateTo({
      url: '../photoalbum/photoalbum?key=' + indexKey
    })
  },

  //打开地图
  openMap: function () {
    console.log(this.data.otherPerInfo.latitude * 1);
    console.log(this.data.otherPerInfo.longitude * 1);
    wx.openLocation({
      latitude: this.data.otherPerInfo.latitude * 1,
      longitude: this.data.otherPerInfo.longitude * 1,
      address: this.data.otherPerInfo.address,
      scale: 18
    })
  },

  //获取小程序码
  getAppletCode: function () {
    this.getAppletQrCode(this);
  },

  //获取小程序码access_token
  getAppletQrCode: function (_that) {
    // var _this = that;
    // var ACCESS_TOKEN = access_token;
    // console.log("_that.data.otherPerInfo==", _that.data.otherPerInfo)
    let qrUrl = "pages/card/otherIndex/otherIndex?openid=" + _that.data.otherOpenid;
    var base64Code = encode.encode(qrUrl);
    app.globalData.qrData = request.request_url+"miniqrQr?path=" + base64Code + "&width=150";
    let transData = {
      name: _that.data.otherPerInfo.userName ? _that.data.otherPerInfo.userName : _that.data.otherPerInfo.nickName,
      avatarUrl: _that.data.otherPerInfo.avatarUrl
    }
    wx.navigateTo({
      url: '../appletQr/appletQr?transData=' + JSON.stringify(transData)
    })
  },

  //获取名片二维码
  goQrcode: function(){
    if (!this.data.otherPerInfo.userName){
      wx.showModal({
        title: "获取二维码失败",
        content: '该用户未完善名片信息',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
      return
    }
    let qrUrl = "pages/card/otherIndex/otherIndex?openid=" + this.data.otherOpenid;
    let base64Code = encode.encode(qrUrl);
    app.globalData.goQrcodeUrl = request.request_url+"miniqrTQr?path=" + base64Code + "&width=140";

    let infoData = {
      avatarUrl: this.data.otherPerInfo.avatarUrl,
      userName: this.data.otherPerInfo.userName,
      title: this.data.otherPerInfo.title,
      mobileNo: this.data.otherPerInfo.mobileNo,
      lawfirmName: this.data.otherPerInfo.lawfirmName,
      email: this.data.otherPerInfo.email,
      seeNum: this.data.otherPerInfo.seeNum,
      voteNum: this.data.otherPerInfo.voteNum,
      msgNum: this.data.msgNum,
      favorNum: this.data.otherPerInfo.favorNum
    };
    wx.navigateTo({
      url: '../qRcode/qRcode?infoData=' + JSON.stringify(infoData)
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getOtherUserInfo(this);
    setTimeout(function () {
      wx.showToast({
        title: '加载成功',
        icon: 'success',
        duration: 1000
      })
      wx.stopPullDownRefresh();
    }, 1000);
    console.log("执行了一次下拉刷新")
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let This = this;
    let titleName = app.globalData.userInfo.nickName + '向您推荐了' + this.data.otherPerInfo.userName;
    return {
      title: titleName,
      path: 'pages/card/otherIndex/otherIndex?openid=' + app.globalData.openid,
      success: function (res) {
        // 转发成功
        console.log("转发成功返回数据=", res)
        wx.showShareMenu({
          // 要求小程序返回分享目标信息
          withShareTicket: true
        });

        if (res.shareTickets) {
          // 获取转发详细信息
          // wx.getShareInfo({
          //   shareTicket: res.shareTickets[0],
          //   success(res) {
          //     // res.errMsg; // 错误信息
          //     // res.encryptedData;  //  解密后为一个 JSON 结构（openGId    群对当前小程序的唯一 ID）
          //     // res.iv; // 加密算法的初始向量
          //     let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
          //     let decodeData = pc.decryptData(res.encryptedData, res.iv);
          //     console.log('解密后 decodeData: ', decodeData);
          //     This.setData({
          //       opengidName: decodeData.openGId
          //     });
          //   },
          //   fail() { },
          //   complete() { }
          // });
        }
      },
      fail: function (res) {
        // 转发失败
      },
      complete: function () {

      }
    }
  }
})